<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    #map{
      width: 800px;
      height: 600px;
      background-color: #ccc;
      position: relative;
    }
    #map div{
      position: absolute;
    }
    
  </style>
</head>
<body>
  <div id='score'>当前分数：0分</div>
  <div id = 'map'></div>
  <script>
    //准备食物数据
    function Food(options){
      this.width = options.width || 20;
      this.height = options.height || 20;
      this.color = options.color || 'green';
      this.map = options.map;
    }
    //将食物显示在地图上(用方法将食物画出来)
    Food.prototype.init = function(){
      //删除旧的食物盒子
      if(this.element){
        this.map.removeChild(this.element)
      }
      //创建新的食物盒子
      var div = document.createElement('div')
      this.element = div;
      div.style.width = this.width + 'px';
      div.style.height = this.height + 'px';
      div.style.backgroundColor = this.color;
      this.map.appendChild(div);
      
      this.randomPos();
    }
    //设置食物显示的随机位置
    Food.prototype.randomPos = function(){
      //先确定食物的随机坐标位置（x 和 y)
      this.x = Math.floor(Math.random() * this.map.offsetWidth / this.width);
      this.y = Math.floor(Math.random() * this.map.offsetHeight / this.height);
      //在确定食物在页面地图中的（top 和 left）
      this.element.style.left = this.x * this.width +'px';
      this.element.style.top = this.y * this.height + 'px';
    }
    //准备小蛇的显示数据
    function Snake(options){
      this.width = options.width || 20;
      this.height = options.height || 20;
      this.color = options.color;
      this.map = options.map;
      this.body = [
        {x:1,y:1,color:'orange'},
        {x:2,y:1,color:'orange'},
        {x:3,y:1,color:'red'}
      ];
      this.elements = [];
      this.fangxiang = 'right'
    }
    //绘制小蛇显示在地图上
    Snake.prototype.init = function(){
      //删除旧蛇
      for(var i =0;i<this.elements.length; i++){
        this.map.removeChild(this.elements[i])
      };
      this.elements=[];
      //创建新蛇
      for(var i = 0; i<this.body.length; i++){
        var div = document.createElement('div')
        this.elements.push(div)
        div.style.width = this.width + 'px';
        div.style.height = this.height + 'px';
        div.style.backgroundColor = this.body[i].color;
        div.style.left = this.body[i].x * this.width +'px';
        div.style.top = this.body[i].y * this.height + 'px';
        this.map.appendChild(div)
      }
    }
    //绘制小蛇让小蛇在地图中移动
    Snake.prototype.move = function(){
      //通过观察 小蛇的身体是复制前一节的坐标  只有头是全新的坐标
      //使得身体移动
      for(var i = 0;i<this.body.length-1;i++){
        this.body[i].x=this.body[i+1].x;
        this.body[i].y=this.body[i+1].y;
      }
      //使得头移动
      //this.body[this.body.length-1].x++
      switch(this.fangxiang){
        case 'left':
          this.body[this.body.length-1].x--;
          break;
        case 'up':
          this.body[this.body.length-1].y--;
          break;
        case 'right':
          this.body[this.body.length-1].x++;
          break;
        case 'down':
          this.body[this.body.length-1].y++;
          break;
      }
    }
    //准备游戏功能中的数据
    function Game(mapDiv,score){
      this.food = new Food({map:mapDiv});
      this.snake = new Snake({map:mapDiv});
      this.map = mapDiv;
      this.score = score;
    }
    //启动游戏功能
    Game.prototype.start = function(){
      //启动绘制小蛇和食物的功能
      this.food.init();
      this.snake.init();
      //让小蛇可以动起来
      this.snakeRun();
      //通过按键控制小蛇的方向
      this.changeDir()
    }
    Game.prototype.snakeRun = function(){
      var snake = this.snake;
      var sheTou = snake.body[snake.body.length-1];
      var food = this.food;
      var sum = 0;
      var score = this.score;
      
      //通过定时器 让小蛇运动
      var timeId = setInterval(function(){
        var sheWeiX = snake.body[0].x;
        var sheWeiY = snake.body[0].y;
        snake.move();
        
      //小蛇吃到食物
      if(sheTou.x === food.x && sheTou.y === food.y){
        snake.body.unshift({x:sheWeiX,y:sheWeiY,color:'blue'})
        sum ++ 
        score.innerText = '当前分数:'+sum*10+'分';
        
        food.init()
      }
      //小蛇撞墙 游戏结束
      if(sheTou.x < 0 || sheTou.y < 0 || sheTou.x > 39 || sheTou.y >29 ){
        alert('撞墙啦 游戏结束')
        clearInterval(timeId)
        return;
      } 
      //小蛇撞到自己 游戏结束
      for(var i=0;i<snake.body.length-4;i++){
        if(sheTou.x === snake.body[i].x && sheTou.y === snake.body[i].y){
          alert('撞到自己 游戏结束')
          clearInterval(timeId)
          return;
        }
      }
      snake.init()
      },150)
    }
    Game.prototype.changeDir = function(){
      var snake = this.snake;
      var flag = true;
      document.onkeydown = function(e){
        if(!flag){
          return;
        }
        flag = false;
        setTimeout(function(){
          flag = true;
        },150)
        //console.log(e.keyCode)
        switch(true){
          case e.keyCode ===37 && snake.fangxiang != 'right':
            snake.fangxiang = 'left'
            break;
          case e.keyCode ===38 && snake.fangxiang != 'down':
            snake.fangxiang = 'up'
            break;
          case e.keyCode ===39 && snake.fangxiang != 'left':
            snake.fangxiang = 'right'
            break;
          case e.keyCode ===40 && snake.fangxiang != 'up':
            snake.fangxiang = 'down'
            break;
        }
      }
    }

    var mapDiv = document.getElementById('map')
    var score = document.getElementById('score')
    var g1 = new Game(mapDiv,score)
    g1.start()


    // var s1 = new Snake({
    //   map:mapDiv
    // })
    // s1.move()

    // var f1 = new Food({
    //   map:mapDiv,
    // })
    // f1.init()
  



  </script>
  
</body>
</html>